import json

from oss2.exceptions import status

from utils import *
from ai_core.core import AiCore
import os
import uuid

class AiVideoClipping():
    def __init__(self, video_id, origin_file_name, model_name):
        self.uuid = video_id  #用指定uuid时使用
        self.accessKeyId = "LTAI5tQ2XoZnvqcVAhXcBLPV"
        self.accessKeySecret = "6sYTwZDPIysms9Z8XN6pGrFCegdE6R"
        self.appKey = "KafwRmZMEt6YnY6u"
        self.origin_audio_path = os.getcwd() + "/origin_audio/" + self.uuid + ".mp3"
        self.origin_video_path = os.getcwd() + "/origin_video/" + origin_file_name
        self.model_name = model_name
        self.audio_recognize_result = os.getcwd() + "/audio_recognize_result/" + self.uuid + ".json"
        self.ai_analysis_result = os.getcwd() + "/ai_analysis_result/" + self.uuid + ".json"
        self.output_video_path = os.getcwd() + "/output_video/" + origin_file_name + self.uuid + ".mp4"
        self.oss_endpoint = "https://oss-cn-beijing.aliyuncs.com"
        self.oss_bucket_name = "clipping-test"
        self.oss_link = "https://clipping-test.oss-cn-beijing.aliyuncs.com"
        self.oss_audio_path = "clipping"
        self.audio_prompt = """以下是一段音频的解析数据，其中BeginTime和EndTime分别代表这一句话的开始时间和结束时间，单位是毫秒，Text是音频识别结果，SpeechRate是语速，数值越大语速越快，EmotionValue是情绪能量值，数值越大代表情绪越强烈。"""
        self.ai_core_prompt = """你需要分析里面你认为最精彩搞笑的所有片段，并截取出来，每段不低于15秒。在思考阶段，你需要综合上下文完整的分析这段精彩搞笑的前因后果，并将该段子全部文本的第一句话的BeginTime与最后一句话的EndTime进行罗列，避免没有上下文导致看不懂的情况。在输出阶段，直接按照以下方式输出一个列表，不要输出其他内容，如：
        [{"BeginTime": "12345", "EndTime": "34567"}, {"BeginTime": "45678", "EndTime": "67890"}]"""
        self.ai_core = AiCore(audio_prompt=self.audio_prompt, ai_core_prompt=self.ai_core_prompt)

    def ai_process(self):
        try:
            with open(self.audio_recognize_result, "r") as json_file:
                data = json.load(json_file)
            message_final = ""
            for message in self.ai_core.run(str(data.get("Result").get("Sentences")), model_name):
                if message.reasoning_content:
                    print(message.reasoning_content, end='')
                elif message.content:
                    print(message.content, end='')
                    message_final += message.content
            with open(self.ai_analysis_result, 'w') as ai_json_file:
                json.dump(message_final, ai_json_file, indent=4)
            return Response(status=True, message="")
        except Exception as e:
            return Response(status=False, message=str(e))

    def run(self):
        # 将视频转换成音频
        response = extract_audio_from_video(self.origin_video_path, self.origin_audio_path)

        # 将音频上传到oss
        response = update_file_to_oss(self.oss_endpoint, self.accessKeyId, self.accessKeySecret, self.oss_bucket_name, self.origin_audio_path, self.oss_audio_path, self.uuid + ".mp3")

        # 下载oss音频并识别，保存到本地
        recognize_link = self.oss_link + "/clipping/" + self.uuid + ".mp3"
        result = fileTrans(self.audio_recognize_result, self.accessKeyId, self.accessKeySecret, self.appKey, recognize_link)

        # 将本地保存的json提取出来并进行ai理解
        response = self.ai_process()

        # 根据json进行视频剪裁
        with open(self.ai_analysis_result, 'r') as ai_json_file:
            data = json.loads(json.load(ai_json_file))
        time_ranges = [(float(d.get("BeginTime"))/1000, float(d.get("EndTime"))/1000) for d in data]
        clip_and_merge_video(self.origin_video_path, self.output_video_path, time_ranges)



if __name__ == '__main__':
    video_id = uuid.uuid4().hex   # 新视频就新生成id
    # video_id = "6b3017dba6664c4eb59fcdc7b72aa847"       # 旧视频直接输入id
    print(video_id)
    origin_file_name = "听泉.mp4"
    model_name = "deepseek-reasoner"    # "deepseek-reasoner"
    ai_video_clipping = AiVideoClipping(video_id, origin_file_name, model_name)
    ai_video_clipping.run()